<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { axiosrnewmedical } from '@/http/axiosRead';
import { showNotify } from 'vant';

// 定义药品类型接口
interface DrugCategory {
  id: number;
  categoryName: string;
}

// 定义药品接口
interface Drug {
  id: number;
  categoryId: number;
  categoryName: string;
  drugName: string;
  dosage: string;
  efficacy: string;
  price: number;
  isPrescription: boolean;
  limitQuantity: number;
  imageUrl: string;
}

// 定义检查类型接口
interface CheckupCategory {
  id: number;
  categoryName: string;
}

// 定义检查项目接口
interface CheckupItem {
  id: number;
  categoryId: number;
  categoryName: string;
  itemName: string;
  price: number;
  notes: string;
}

// 定义检验类型接口
interface TestCategory {
  id: number;
  categoryName: string;
}

// 定义检验项目接口
interface TestItem {
  id: number;
  categoryId: number;
  categoryName: string;
  itemName: string;
  price: number;
}

// 购物车项目接口
interface CartItem {
  drug?: Drug;
  checkupItem?: CheckupItem;
  testItem?: TestItem;
  quantity: number;
}

const router = useRouter();
const route = useRoute();
// 保存医院ID和名称，可用于后续提交订单时使用
const hospitalId = ref(route.query.hospitalId as string);
const hospitalName = ref(route.query.hospitalName as string);

const activeTab = ref('药品');
const categories = ref<DrugCategory[]>([]);
const drugs = ref<Drug[]>([]);
const selectedCategory = ref<DrugCategory | null>(null);
const loading = ref(false);
const cartItems = ref<CartItem[]>([]);

// 购物车弹窗控制
const showCartPopup = ref(false);

// 检查相关的状态
const checkupCategories = ref<CheckupCategory[]>([]);
const checkupItems = ref<CheckupItem[]>([]);
const selectedCheckupCategory = ref<CheckupCategory | null>(null);
const checkupLoading = ref(false);

// 检验相关的状态
const testCategories = ref<TestCategory[]>([]);
const testItems = ref<TestItem[]>([]);
const selectedTestCategory = ref<TestCategory | null>(null);
const testLoading = ref(false);

// 计算购物车总数和总价
const cartTotal = computed(() => {
  const total = cartItems.value.reduce((sum, item) => {
    if (item.drug) {
      return sum + item.drug.price * item.quantity;
    } else if (item.checkupItem) {
      return sum + item.checkupItem.price * item.quantity;
    } else if (item.testItem) {
      return sum + item.testItem.price * item.quantity;
    }
    return sum;
  }, 0);
  return total.toFixed(2);
});

const cartCount = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + item.quantity, 0);
});

const goBack = () => {
  router.back();
};

// 获取药品分类
const fetchCategories = async () => {
  loading.value = true;
  try {
    const response = await axiosrnewmedical.get('/Drug/categories');
    if (response.data.code === 200 && response.data.data) {
      categories.value = response.data.data;
      if (categories.value.length > 0) {
        selectedCategory.value = categories.value[0];
        fetchDrugs(categories.value[0].id);
      }
    } else {
      console.error('获取药品分类失败:', response.data.msg);
      // 添加示例数据
      categories.value = [
        { id: 1, categoryName: '新冠预防中药' },
        { id: 2, categoryName: '普通用药' },
        { id: 3, categoryName: '感冒用药（非处方）' }
      ];
      selectedCategory.value = categories.value[0];
      fetchDrugs(categories.value[0].id);
    }
  } catch (error) {
    console.error('获取药品分类请求错误:', error);
    // 添加示例数据
    categories.value = [
      { id: 1, categoryName: '新冠预防中药' },
      { id: 2, categoryName: '普通用药' },
      { id: 3, categoryName: '感冒用药（非处方）' }
    ];
    selectedCategory.value = categories.value[0];
    fetchDrugs(categories.value[0].id);
  } finally {
    loading.value = false;
  }
};

// 获取药品列表
const fetchDrugs = async (categoryId: number) => {
  loading.value = true;
  try {
    // 修正API路径，确保与服务器匹配
    const response = await axiosrnewmedical.get('/Doctor/Drug/GetDrugs', {
      params: { categoryId: categoryId }
    });
    if (response.data.code === 200 && response.data.data) {
      drugs.value = response.data.data;
    } else {
      console.error('获取药品列表失败:', response.data.msg);
      // 添加示例数据
      if (categoryId === 1) {
        drugs.value = [
          { 
            id: 1, 
            categoryId: 1, 
            categoryName: '新冠预防中药', 
            drugName: '新冠预防中药（正常人群）', 
            dosage: '1剂', 
            efficacy: '主要提高免疫力，预防新冠疾病', 
            price: 10.08, 
            isPrescription: true, 
            limitQuantity: 5, 
            imageUrl: '' 
          },
          { 
            id: 2, 
            categoryId: 1, 
            categoryName: '新冠预防中药', 
            drugName: '新冠预防中药（体弱人群）', 
            dosage: '1剂', 
            efficacy: '主要提高免疫力，预防新冠疾病', 
            price: 11.80, 
            isPrescription: true, 
            limitQuantity: 5, 
            imageUrl: '' 
          },
          { 
            id: 3, 
            categoryId: 1, 
            categoryName: '新冠预防中药', 
            drugName: '新冠预防中药（儿童人群）', 
            dosage: '1剂', 
            efficacy: '主要提高免疫力，预防新冠疾病', 
            price: 9.80, 
            isPrescription: true, 
            limitQuantity: 5, 
            imageUrl: '' 
          }
        ];
      } else {
        drugs.value = [];
      }
    }
  } catch (error) {
    console.error('获取药品列表请求错误:', error);
    // 添加示例数据
    if (categoryId === 1) {
      drugs.value = [
        { 
          id: 1, 
          categoryId: 1, 
          categoryName: '新冠预防中药', 
          drugName: '新冠预防中药（正常人群）', 
          dosage: '1剂', 
          efficacy: '主要提高免疫力，预防新冠疾病', 
          price: 10.08, 
          isPrescription: true, 
          limitQuantity: 5, 
          imageUrl: '' 
        },
        { 
          id: 2, 
          categoryId: 1, 
          categoryName: '新冠预防中药', 
          drugName: '新冠预防中药（体弱人群）', 
          dosage: '1剂', 
          efficacy: '主要提高免疫力，预防新冠疾病', 
          price: 11.80, 
          isPrescription: true, 
          limitQuantity: 5, 
          imageUrl: '' 
        },
        { 
          id: 3, 
          categoryId: 1, 
          categoryName: '新冠预防中药', 
          drugName: '新冠预防中药（儿童人群）', 
          dosage: '1剂', 
          efficacy: '主要提高免疫力，预防新冠疾病', 
          price: 9.80, 
          isPrescription: true, 
          limitQuantity: 5, 
          imageUrl: '' 
        }
      ];
    } else {
      drugs.value = [];
    }
  } finally {
    loading.value = false;
  }
};

// 选择药品分类
const selectCategory = (category: DrugCategory) => {
  selectedCategory.value = category;
  fetchDrugs(category.id);
};

// 获取检查类型
const fetchCheckupCategories = async () => {
  checkupLoading.value = true;
  try {
    const response = await axiosrnewmedical.get('/Checkup/categories');
    if (response.data.code === 200 && response.data.data) {
      checkupCategories.value = response.data.data;
      if (checkupCategories.value.length > 0) {
        selectedCheckupCategory.value = checkupCategories.value[0];
        fetchCheckupItems(checkupCategories.value[0].id);
      }
    } else {
      console.error('获取检查类型失败:', response.data.msg);
      // 添加示例数据
      checkupCategories.value = [
        { id: 1, categoryName: '心电血压' },
        { id: 2, categoryName: '放射岩熙' },
        { id: 3, categoryName: '超声检查' }
      ];
      selectedCheckupCategory.value = checkupCategories.value[0];
      fetchCheckupItems(checkupCategories.value[0].id);
    }
  } catch (error) {
    console.error('获取检查类型请求错误:', error);
    // 添加示例数据
    checkupCategories.value = [
      { id: 1, categoryName: '心电血压' },
      { id: 2, categoryName: '放射岩熙' },
      { id: 3, categoryName: '超声检查' }
    ];
    selectedCheckupCategory.value = checkupCategories.value[0];
    fetchCheckupItems(checkupCategories.value[0].id);
  } finally {
    checkupLoading.value = false;
  }
};

// 获取检查项目列表
const fetchCheckupItems = async (categoryId: number) => {
  checkupLoading.value = true;
  try {
    const response = await axiosrnewmedical.get('/Checkup/GetCheckupItems', {
      params: { categoryId: categoryId }
    });
    if (response.data.code === 200 && response.data.data) {
      checkupItems.value = response.data.data;
    } else {
      console.error('获取检查项目失败:', response.data.msg);
      // 添加示例数据
      if (categoryId === 1) {
        checkupItems.value = [
          { 
            id: 1, 
            categoryId: 1, 
            categoryName: '心电血压', 
            itemName: '动态心电图', 
            price: 150.00, 
            notes: '注意事项' 
          },
          { 
            id: 2, 
            categoryId: 1, 
            categoryName: '心电血压', 
            itemName: '12号同步心电图检查', 
            price: 30.00, 
            notes: '' 
          }
        ];
      } else {
        checkupItems.value = [];
      }
    }
  } catch (error) {
    console.error('获取检查项目请求错误:', error);
    // 添加示例数据
    if (categoryId === 1) {
      checkupItems.value = [
        { 
          id: 1, 
          categoryId: 1, 
          categoryName: '心电血压', 
          itemName: '动态心电图', 
          price: 150.00, 
          notes: '注意事项' 
        },
        { 
          id: 2, 
          categoryId: 1, 
          categoryName: '心电血压', 
          itemName: '12号同步心电图检查', 
          price: 30.00, 
          notes: '' 
        }
      ];
    } else {
      checkupItems.value = [];
    }
  } finally {
    checkupLoading.value = false;
  }
};

// 选择检查类型
const selectCheckupCategory = (category: CheckupCategory) => {
  selectedCheckupCategory.value = category;
  fetchCheckupItems(category.id);
};

// 添加检查项目到购物车
const addCheckupToCart = (item: CheckupItem) => {
  const existingItem = cartItems.value.find(cartItem => cartItem.checkupItem?.id === item.id);
  if (existingItem) {
    // 如果项目已经在购物车中，则删除
    const index = cartItems.value.findIndex(cartItem => cartItem.checkupItem?.id === item.id);
    if (index !== -1) {
      cartItems.value.splice(index, 1);
    }
  } else {
    // 添加新项目到购物车
    cartItems.value.push({ checkupItem: item, quantity: 1 });
  }
};

// 添加药品到购物车
const addToCart = (drug: Drug) => {
  const existingItem = cartItems.value.find(item => item.drug?.id === drug.id);
  if (existingItem) {
    if (existingItem.quantity < (drug.limitQuantity || 99)) {
      existingItem.quantity++;
    }
  } else {
    cartItems.value.push({ drug, quantity: 1 });
  }
};

// 减少购物车中药品数量
const decreaseQuantity = (drug: Drug) => {
  const index = cartItems.value.findIndex(item => item.drug?.id === drug.id);
  if (index !== -1) {
    if (cartItems.value[index].quantity > 1) {
      cartItems.value[index].quantity--;
    } else {
      cartItems.value.splice(index, 1);
    }
  }
};

// 获取检验类型
const fetchTestCategories = async () => {
  testLoading.value = true;
  try {
    const response = await axiosrnewmedical.get('/Test/categories');
    if (response.data.code === 200 && response.data.data) {
      testCategories.value = response.data.data;
      if (testCategories.value.length > 0) {
        selectedTestCategory.value = testCategories.value[0];
        fetchTestItems(testCategories.value[0].id);
      }
    } else {
      console.error('获取检验类型失败:', response.data.msg);
      // 添加示例数据
      testCategories.value = [
        { id: 1, categoryName: '血常规+生化检查' },
        { id: 2, categoryName: '免疫血液检查' },
        { id: 3, categoryName: '体检检查' }
      ];
      selectedTestCategory.value = testCategories.value[0];
      fetchTestItems(testCategories.value[0].id);
    }
  } catch (error) {
    console.error('获取检验类型请求错误:', error);
    // 添加示例数据
    testCategories.value = [
      { id: 1, categoryName: '血常规+生化检查' },
      { id: 2, categoryName: '免疫血液检查' },
      { id: 3, categoryName: '体检检查' }
    ];
    selectedTestCategory.value = testCategories.value[0];
    fetchTestItems(testCategories.value[0].id);
  } finally {
    testLoading.value = false;
  }
};

// 获取检验项目列表
const fetchTestItems = async (categoryId: number) => {
  testLoading.value = true;
  try {
    const response = await axiosrnewmedical.get('/Test/GetTestItems', {
      params: { categoryId: categoryId }
    });
    if (response.data.code === 200 && response.data.data) {
      testItems.value = response.data.data;
    } else {
      console.error('获取检验项目失败:', response.data.msg);
      // 添加示例数据
      if (categoryId === 1) {
        testItems.value = [
          { 
            id: 1, 
            categoryId: 1, 
            categoryName: '血常规+生化检查', 
            itemName: '血常规', 
            price: 15.00
          },
          { 
            id: 2, 
            categoryId: 1, 
            categoryName: '血常规+生化检查', 
            itemName: '血常规+网织红细胞', 
            price: 38.00
          },
          { 
            id: 3, 
            categoryId: 1, 
            categoryName: '血常规+生化检查', 
            itemName: '肝功', 
            price: 38.00
          },
          { 
            id: 4, 
            categoryId: 1, 
            categoryName: '血常规+生化检查', 
            itemName: '肾功', 
            price: 24.00
          }
        ];
      } else {
        testItems.value = [];
      }
    }
  } catch (error) {
    console.error('获取检验项目请求错误:', error);
    // 添加示例数据
    if (categoryId === 1) {
      testItems.value = [
        { 
          id: 1, 
          categoryId: 1, 
          categoryName: '血常规+生化检查', 
          itemName: '血常规', 
          price: 15.00
        },
        { 
          id: 2, 
          categoryId: 1, 
          categoryName: '血常规+生化检查', 
          itemName: '血常规+网织红细胞', 
          price: 38.00
        },
        { 
          id: 3, 
          categoryId: 1, 
          categoryName: '血常规+生化检查', 
          itemName: '肝功', 
          price: 38.00
        },
        { 
          id: 4, 
          categoryId: 1, 
          categoryName: '血常规+生化检查', 
          itemName: '肾功', 
          price: 24.00
        }
      ];
    } else {
      testItems.value = [];
    }
  } finally {
    testLoading.value = false;
  }
};

// 选择检验类型
const selectTestCategory = (category: TestCategory) => {
  selectedTestCategory.value = category;
  fetchTestItems(category.id);
};

// 添加检验项目到购物车
const addTestToCart = (item: TestItem) => {
  const existingItem = cartItems.value.find(cartItem => cartItem.testItem?.id === item.id);
  if (existingItem) {
    // 如果项目已经在购物车中，则删除
    const index = cartItems.value.findIndex(cartItem => cartItem.testItem?.id === item.id);
    if (index !== -1) {
      cartItems.value.splice(index, 1);
    }
  } else {
    // 添加新项目到购物车
    cartItems.value.push({ testItem: item, quantity: 1 });
  }
};

// 提交订单
const submitOrder = () => {
  // 检查是否有选中的项目
  if (cartItems.value.length === 0) {
    showNotify({ type: 'warning', message: '请选择要购买的商品或服务' });
    return;
  }
  
  // 将购物车数据保存到localStorage
  localStorage.setItem('selectedItems', JSON.stringify(cartItems.value));
  
  // 保存医院信息
  if (hospitalId.value && hospitalName.value) {
    localStorage.setItem('hospitalId', hospitalId.value);
    localStorage.setItem('hospitalName', hospitalName.value);
  }
  
  // 关闭弹窗
  showCartPopup.value = false;
  
  // 跳转到确认页面
  router.push('/order-confirm');
};

// 清空购物车
const clearCart = () => {
  cartItems.value = [];
  showCartPopup.value = false;
};

// 监听标签页切换
const handleTabChange = (tabName: string) => {
  if (tabName === '开单记录') {
    // 跳转到开单记录页面
    router.push('/prescription-record');
    return;
  }
  
  activeTab.value = tabName;
  if (tabName === '检查') {
    fetchCheckupCategories();
  } else if (tabName === '药品') {
    fetchCategories();
  } else if (tabName === '检验') {
    fetchTestCategories();
  }
};

onMounted(() => {
  fetchCategories();
});
</script>

<template>
  <div class="drug-order-page">
    <van-nav-bar
      title="开单申请"
      left-arrow
      @click-left="goBack"
    >
      <template #right>
        <div class="nav-icons">
          <span class="dot"></span>
          <span class="dot"></span>
          <span class="dot"></span>
          <span class="circle-btn"></span>
        </div>
      </template>
    </van-nav-bar>

    <!-- 顶部标签栏 -->
    <div class="tab-header">
      <div class="tab-items">
        <div 
          class="tab-item" 
          :class="{ active: activeTab === '药品' }"
          @click="handleTabChange('药品')"
        >药品</div>
        <div 
          class="tab-item" 
          :class="{ active: activeTab === '检查' }"
          @click="handleTabChange('检查')"
        >检查</div>
        <div 
          class="tab-item" 
          :class="{ active: activeTab === '检验' }"
          @click="handleTabChange('检验')"
        >检验</div>
      </div>
      <div class="record-link" @click="router.push('/prescription-record')">
        开单记录 >
      </div>
    </div>

    <!-- 药品模块 -->
    <div v-if="activeTab === '药品'" class="module-container">
      <div class="category-sidebar">
        <div 
          v-for="category in categories" 
          :key="category.id" 
          class="category-item"
          :class="{ 'active': selectedCategory?.id === category.id }"
          @click="selectCategory(category)"
        >
          {{ category.categoryName }}
        </div>
      </div>
      
      <div class="item-list">
        <van-loading v-if="loading" class="loading-spinner" />
        
        <div v-else>
          <div v-for="drug in drugs" :key="drug.id" class="drug-card">
            <div class="drug-card-left">
              <div class="drug-image">
                <img :src="drug.imageUrl || '/images/hospital.png'" alt="药品图片">
              </div>
            </div>
            <div class="drug-card-right">
              <div class="drug-name">{{ drug.drugName }}</div>
              <div class="drug-efficacy">功效: {{ drug.efficacy }}</div>
              <div class="drug-price">￥{{ drug.price.toFixed(2) }}</div>
              
              <div class="action-row">
                <div class="drug-tags">
                  <span class="prescription-tag" v-if="drug.isPrescription">处方药</span>
                  <span class="limit-tag" v-if="drug.limitQuantity">限购{{ drug.limitQuantity }}剂</span>
                </div>
                <div class="quantity-control">
                  <button class="decrease" @click="decreaseQuantity(drug)">-</button>
                  <span class="quantity">{{ cartItems.find(item => item.drug?.id === drug.id)?.quantity || 0 }}</span>
                  <button class="increase" @click="addToCart(drug)">+</button>
                </div>
              </div>
            </div>
          </div>
          
          <div v-if="drugs.length === 0" class="empty-state">
            该分类下暂无药品
          </div>
        </div>
      </div>
    </div>

    <!-- 检查模块 -->
    <div v-else-if="activeTab === '检查'" class="module-container">
      <div class="category-sidebar">
        <div 
          v-for="category in checkupCategories" 
          :key="category.id" 
          class="category-item"
          :class="{ 'active': selectedCheckupCategory?.id === category.id }"
          @click="selectCheckupCategory(category)"
        >
          {{ category.categoryName }}
        </div>
      </div>
      
      <div class="item-list">
        <van-loading v-if="checkupLoading" class="loading-spinner" />
        
        <div v-else>
          <div v-for="item in checkupItems" :key="item.id" class="checkup-item">
            <div class="checkup-item-content">
              <div class="checkup-name">{{ item.itemName }}</div>
              <div class="checkup-price">￥{{ item.price.toFixed(2) }}/次</div>
              <div v-if="item.notes" class="checkup-notes">{{ item.notes }}</div>
            </div>
            <div class="checkup-select" @click="addCheckupToCart(item)">
              <div class="select-circle" :class="{ 'selected': !!cartItems.find(cartItem => cartItem.checkupItem?.id === item.id) }">
                <span v-if="!!cartItems.find(cartItem => cartItem.checkupItem?.id === item.id)" class="check-icon">✓</span>
              </div>
            </div>
          </div>
          
          <div v-if="checkupItems.length === 0" class="empty-state">
            该分类下暂无检查项目
          </div>
        </div>
      </div>
    </div>
    
    <!-- 检验模块 -->
    <div v-else-if="activeTab === '检验'" class="module-container">
      <div class="category-sidebar">
        <div 
          v-for="category in testCategories" 
          :key="category.id" 
          class="category-item"
          :class="{ 'active': selectedTestCategory?.id === category.id }"
          @click="selectTestCategory(category)"
        >
          {{ category.categoryName }}
        </div>
      </div>
      
      <div class="item-list">
        <van-loading v-if="testLoading" class="loading-spinner" />
        
        <div v-else>
          <div v-for="item in testItems" :key="item.id" class="checkup-item">
            <div class="checkup-item-content">
              <div class="checkup-name">{{ item.itemName }}</div>
              <div class="checkup-price">￥{{ item.price.toFixed(2) }}/次</div>
            </div>
            <div class="checkup-select" @click="addTestToCart(item)">
              <div class="select-circle" :class="{ 'selected': !!cartItems.find(cartItem => cartItem.testItem?.id === item.id) }">
                <span v-if="!!cartItems.find(cartItem => cartItem.testItem?.id === item.id)" class="check-icon">✓</span>
              </div>
            </div>
          </div>
          
          <div v-if="testItems.length === 0" class="empty-state">
            该分类下暂无检验项目
          </div>
        </div>
      </div>
    </div>

    <!-- 底部购物车总结区域 -->
    <div class="cart-summary-footer" v-if="cartCount > 0">
      <div class="cart-summary-container">
        <!-- 购物车图标和已选信息 -->
        <div class="cart-info-section" @click="showCartPopup = true">
          <div class="cart-icon-wrapper">
            <van-icon name="shopping-cart-o" class="cart-icon" />
            <div class="cart-badge" v-if="cartCount > 0">{{ cartCount }}</div>
          </div>
          <div class="cart-details">
            <div class="cart-text">已选 <span class="cart-count">{{ cartCount }}</span> 项</div>
            <div class="cart-total-price">合计: <span class="price-amount">￥{{ cartTotal }}</span></div>
          </div>
        </div>
        
        <!-- 提交按钮 -->
        <div class="confirm-submit-btn" @click="submitOrder">
          提交
        </div>
      </div>
    </div>

    <!-- 已选项目弹窗 -->
    <van-popup v-model:show="showCartPopup" position="bottom" round :style="{ maxHeight: '75%' }">
      <div class="cart-popup">
        <div class="cart-popup-header">
          <div class="cart-popup-title">已选项目</div>
          <div class="clear-cart" @click="clearCart">全部清空</div>
        </div>
        <div class="cart-popup-content">
          <div v-if="cartItems.length === 0" class="empty-cart">
            购物车为空
          </div>
          <div v-else>
            <!-- 药品项目 -->
            <div v-for="(item, index) in cartItems" :key="index" class="cart-popup-item">
              <div class="cart-item-left">
                <div class="cart-item-type" v-if="item.drug">药</div>
                <div class="cart-item-type" v-else-if="item.checkupItem">查</div>
                <div class="cart-item-type" v-else-if="item.testItem">验</div>
              </div>
              <div class="cart-item-middle">
                <div class="cart-item-name">
                  {{ item.drug?.drugName || item.checkupItem?.itemName || item.testItem?.itemName }}
                </div>
                <div class="cart-item-price">
                  <span class="cart-item-price-tag" v-if="item.drug">
                    ￥{{ item.drug.price.toFixed(2) }}/剂
                  </span>
                  <span class="cart-item-price-tag" v-else-if="item.checkupItem">
                    ￥{{ item.checkupItem.price.toFixed(2) }}/次
                  </span>
                  <span class="cart-item-price-tag" v-else-if="item.testItem">
                    ￥{{ item.testItem.price.toFixed(2) }}/次
                  </span>
                </div>
                <div class="cart-item-tag" v-if="item.drug && item.drug.isPrescription">处方药</div>
              </div>
              <div class="cart-item-right">
                <div class="quantity-control" v-if="item.drug">
                  <button class="decrease" @click="decreaseQuantity(item.drug)">-</button>
                  <span class="quantity">{{ item.quantity }}</span>
                  <button class="increase" @click="item.quantity < (item.drug.limitQuantity || 99) ? item.quantity++ : null">+</button>
                </div>
                <div class="cart-item-check" v-else>
                  <div class="select-circle selected">
                    <span class="check-icon">✓</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 弹窗底部总结和提交按钮 -->
        <div class="cart-popup-footer" v-if="cartItems.length > 0">
          <div class="popup-summary">
            <div class="popup-summary-left">
              <div class="popup-summary-icon">🛍</div>
              <div class="popup-summary-info">
                <div class="popup-item-count">已选 {{ cartCount }} 项</div>
                <div class="popup-total-price">合计: <span class="popup-price">￥{{ cartTotal }}</span></div>
              </div>
            </div>
            <div class="popup-submit-btn" @click="submitOrder">
              提交
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<style scoped>
.drug-order-page {
  background: #f8f9fa;
  min-height: 100vh;
  padding-bottom: 60px;
}

.nav-icons {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dot {
  width: 6px;
  height: 6px;
  background: #d8d8d8;
  border-radius: 50%;
  display: inline-block;
}

.circle-btn {
  width: 18px;
  height: 18px;
  border: 1.5px solid #d8d8d8;
  border-radius: 50%;
  display: inline-block;
  margin-left: 6px;
}

/* 标签样式 */
.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  background: #fff;
  border-bottom: 1px solid #eee;
}

.tab-items {
  display: flex;
}

.tab-item {
  padding: 12px 15px;
  font-size: 15px;
  position: relative;
  cursor: pointer;
}

.tab-item.active {
  color: #1989fa;
  font-weight: 500;
}

.tab-item.active::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 15px;
  right: 15px;
  height: 2px;
  background: #1989fa;
  border-radius: 1px;
}

.record-link {
  color: #1989fa;
  font-size: 14px;
}

.module-container {
  display: flex;
  height: calc(100vh - 110px);
}

.category-sidebar {
  width: 100px;
  background: #f5f5f5;
  overflow-y: auto;
  height: 100%;
}

.category-item {
  padding: 15px 10px;
  text-align: center;
  font-size: 14px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
}

.category-item.active {
  background: #fff;
  color: #1989fa;
  font-weight: 500;
}

.item-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.loading-spinner {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

/* 药品卡片样式 */
.drug-card {
  background: #fff;
  margin-bottom: 12px;
  padding: 15px;
  display: flex;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.drug-card-left {
  margin-right: 12px;
}

.drug-card-right {
  flex: 1;
}

.drug-image {
  width: 80px;
  height: 80px;
  background: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.drug-image img {
  width: 70px;
  height: 70px;
  object-fit: contain;
}

.drug-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 6px;
}

.drug-efficacy {
  font-size: 13px;
  color: #999;
  margin-bottom: 6px;
}

.drug-price {
  color: #f56c6c;
  font-size: 17px;
  font-weight: 500;
  margin-bottom: 10px;
}

.action-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.drug-tags {
  display: flex;
  gap: 8px;
}

.prescription-tag, .limit-tag {
  font-size: 12px;
  color: #1989fa;
  padding: 2px 6px;
  border-radius: 4px;
  background: #e6f0ff;
}

.quantity-control {
  display: flex;
  align-items: center;
}

.decrease, .increase {
  width: 26px;
  height: 26px;
  border-radius: 50%;
  border: 1px solid #ddd;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  cursor: pointer;
}

.quantity {
  margin: 0 12px;
  min-width: 20px;
  text-align: center;
}

/* 检查项目样式 */
.checkup-item {
  background: #fff;
  margin-bottom: 1px;
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f2f2f2;
  box-shadow: none;
  border-radius: 0;
}

.checkup-item-content {
  flex: 1;
}

.checkup-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 6px;
}

.checkup-price {
  color: #f56c6c;
  font-size: 15px;
  margin-bottom: 6px;
}

.checkup-notes {
  font-size: 12px;
  color: #ff9900;
  padding: 2px 6px;
  background-color: #fff9f0;
  border-radius: 2px;
  display: inline-block;
}

.checkup-select {
  margin-left: 10px;
}

.select-circle {
  width: 22px;
  height: 22px;
  border-radius: 50%;
  border: 1px solid #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.select-circle.selected {
  background-color: #1989fa;
  border-color: #1989fa;
}

.check-icon {
  color: white;
  font-size: 14px;
  font-weight: bold;
}

.checkup-checkbox {
  font-size: 20px;
  color: #1989fa;
}

.empty-state {
  text-align: center;
  color: #999;
  padding: 40px 0;
}

/* 底部购物车总结区域样式 */
.cart-summary-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  border-top: 1px solid #eee;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.1);
  z-index: 999;
  padding: 12px 16px;
}

.cart-summary-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.cart-info-section {
  display: flex;
  align-items: center;
  flex: 1;
  cursor: pointer;
}

.cart-icon-wrapper {
  position: relative;
  margin-right: 12px;
}

.cart-icon {
  font-size: 24px;
  color: #1989fa;
}

.cart-badge {
  position: absolute;
  top: -6px;
  right: -6px;
  background: #ff4757;
  color: white;
  font-size: 10px;
  font-weight: bold;
  padding: 2px 6px;
  border-radius: 10px;
  min-width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 1px 3px rgba(255, 71, 87, 0.3);
}

.cart-details {
  flex: 1;
}

.cart-text {
  font-size: 14px;
  color: #333;
  margin-bottom: 2px;
}

.cart-count {
  color: #1989fa;
  font-weight: 600;
}

.cart-total-price {
  font-size: 15px;
  color: #333;
}

.price-amount {
  color: #ff4757;
  font-weight: 600;
  font-size: 16px;
}

.confirm-submit-btn {
  background: linear-gradient(135deg, #1989fa 0%, #1c7ed6 100%);
  color: white;
  padding: 12px 32px;
  border-radius: 24px;
  font-size: 15px;
  font-weight: 600;
  cursor: pointer;
  border: none;
  box-shadow: 0 3px 12px rgba(25, 137, 250, 0.3);
  transition: all 0.3s ease;
  letter-spacing: 0.5px;
}

.confirm-submit-btn:active {
  transform: translateY(1px);
  box-shadow: 0 2px 8px rgba(25, 137, 250, 0.4);
}

/* 购物车弹窗样式 */
.cart-popup {
  padding: 15px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.cart-popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.cart-popup-title {
  font-size: 18px;
  font-weight: 500;
}

.clear-cart {
  color: #1989fa;
  font-size: 14px;
  cursor: pointer;
}

.cart-popup-content {
  flex: 1;
  overflow-y: auto;
}

.empty-cart {
  text-align: center;
  color: #999;
  padding: 40px 0;
}

.cart-popup-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

.cart-item-left {
  width: 30px;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  color: #1989fa;
}

.cart-item-middle {
  flex: 1;
  margin-left: 15px;
}

.cart-item-name {
  font-size: 15px;
  font-weight: 500;
  margin-bottom: 4px;
}

.cart-item-price {
  font-size: 14px;
  color: #f56c6c;
  margin-bottom: 4px;
}

.cart-item-price-tag {
  font-weight: 500;
}

.cart-item-tag {
  font-size: 12px;
  color: #1989fa;
  padding: 2px 6px;
  border-radius: 4px;
  background: #e6f0ff;
}

.cart-item-right {
  width: 80px;
  text-align: right;
}

.quantity-control {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.quantity-control .decrease,
.quantity-control .increase {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  border: 1px solid #ddd;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  cursor: pointer;
}

.quantity-control .quantity {
  margin: 0 10px;
  min-width: 20px;
  text-align: center;
}

.cart-item-check {
  margin-left: 10px;
}

.cart-item-check .select-circle {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 1px solid #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.cart-item-check .select-circle.selected {
  background-color: #1989fa;
  border-color: #1989fa;
}

.cart-item-check .check-icon {
  color: white;
  font-size: 12px;
  font-weight: bold;
}

/* 购物车弹窗底部样式 */
.cart-popup-footer {
  border-top: 1px solid #eee;
  padding: 12px 0;
  background: #fff;
  border-radius: 0 0 16px 16px;
}

.popup-summary {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.popup-summary-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.popup-summary-icon {
  font-size: 24px;
  margin-right: 12px;
}

.popup-summary-info {
  flex: 1;
}

.popup-item-count {
  font-size: 14px;
  color: #333;
  margin-bottom: 2px;
}

.popup-total-price {
  font-size: 15px;
  color: #333;
}

.popup-price {
  color: #ff4757;
  font-weight: 600;
  font-size: 16px;
}

.popup-submit-btn {
  background: linear-gradient(135deg, #1989fa 0%, #1c7ed6 100%);
  color: white;
  padding: 12px 32px;
  border-radius: 24px;
  font-size: 15px;
  font-weight: 600;
  cursor: pointer;
  border: none;
  box-shadow: 0 3px 12px rgba(25, 137, 250, 0.3);
  transition: all 0.3s ease;
  letter-spacing: 0.5px;
}

.popup-submit-btn:active {
  transform: translateY(1px);
  box-shadow: 0 2px 8px rgba(25, 137, 250, 0.4);
}
</style> 